package com.ruoyi.system.service.impl;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Echarts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.StuCertificateMapper;
import com.ruoyi.system.domain.StuCertificate;
import com.ruoyi.system.service.IStuCertificateService;
import com.ruoyi.common.core.text.Convert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.ruoyi.common.config.datasource.DynamicDataSourceContextHolder.log;

/**
 * 资格证书Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-09
 */
@Service
public class StuCertificateServiceImpl implements IStuCertificateService 
{
    @Autowired
    private StuCertificateMapper stuCertificateMapper;

    /**
     * 查询资格证书
     * 
     * @param cerId 资格证书主键
     * @return 资格证书
     */
    @Override
    public StuCertificate selectStuCertificateByCerId(Long cerId)
    {
        return stuCertificateMapper.selectStuCertificateByCerId(cerId);
    }

    /**
     * 查询资格证书列表
     * 
     * @param stuCertificate 资格证书
     * @return 资格证书
     */
    @Override
    @DataScope(deptAlias = "u", userAlias = "u")
    public List<StuCertificate> selectStuCertificateList(StuCertificate stuCertificate)
    {
        return stuCertificateMapper.selectStuCertificateList(stuCertificate);
    }

    /**
     * 新增资格证书
     * 
     * @param stuCertificate 资格证书
     * @return 结果
     */
    @Override
    public int insertStuCertificate(StuCertificate stuCertificate)
    {
        return stuCertificateMapper.insertStuCertificate(stuCertificate);
    }

    /**
     * 修改资格证书
     * 
     * @param stuCertificate 资格证书
     * @return 结果
     */
    @Override
    public int updateStuCertificate(StuCertificate stuCertificate)
    {
        return stuCertificateMapper.updateStuCertificate(stuCertificate);
    }

    /**
     * 批量删除资格证书
     * 
     * @param cerIds 需要删除的资格证书主键
     * @return 结果
     */
    @Override
    public int deleteStuCertificateByCerIds(String cerIds)
    {
        String[] array = Convert.toStrArray(cerIds);
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
        return stuCertificateMapper.deleteStuCertificateByCerIds(Convert.toStrArray(cerIds));
    }

    /**
     * 删除资格证书信息
     * 
     * @param cerId 资格证书主键
     * @return 结果
     */
    @Override
    public int deleteStuCertificateByCerId(Long cerId)
    {
        return stuCertificateMapper.deleteStuCertificateByCerId(cerId);
    }

    @Override
    public List<StuCertificate> selectStuCertificateByCerIds(String cerIds) {
        String[] array = Convert.toStrArray(cerIds);
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
        return stuCertificateMapper.selectStuCertificateByCerIds(Convert.toStrArray(cerIds));
    }

    @Override
    public void downloadFiles(String cerIds, HttpServletRequest request, HttpServletResponse response) {
        // 以逗号分割字符串，输出成数组
        String[] array = Convert.toStrArray(cerIds);
        // 本地资源路径
        String localPath = RuoYiConfig.getProfile();;
        StuCertificate stuCertificate;
        //获取文件路径
        String filePaths;
        //文件后缀
        String fileExtend;
        //文件显示名称
        String nameShow;
        List<Map> fileList = new ArrayList();
        for (int i = 0; i < array.length; i++)
        {
            HashMap map = new HashMap();
            stuCertificate = stuCertificateMapper.selectStuCertificateByCerId(Convert.toLong(array[i]));

            filePaths = localPath + StringUtils.substringAfter(stuCertificate.getFilePath(), Constants.RESOURCE_PREFIX);

            fileExtend = StringUtils.substringAfterLast(filePaths, ".");

            nameShow = stuCertificate.getCerName() + "_" + stuCertificate.getStuNumber() + "_" + stuCertificate.getStuName() + "_" + array[i] + "." + fileExtend;
            //设置参数

            map.put("nameShow", nameShow);
            try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                //创建文件输入流
                FileInputStream fis = new FileInputStream(filePaths);
                BufferedInputStream bis = new BufferedInputStream(fis);
                //字节输出流，注意要全部读取完成才能进行下一步
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int c = bis.read();//读取bis流中的下一个字节
                while (c != -1) {
                    baos.write(c);
                    c = bis.read();
                }
                bis.close();
                byte retArr[] = baos.toByteArray();
                map.put("outByte", retArr);
                fileList.add(map);
                bis.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        zipFiles(fileList,response);
    }


    //多个文件压缩成压缩包并下载
    public void zipFiles(List<Map> fileList, HttpServletResponse httpResponse) {

        try(ZipOutputStream zipOutputStream = new ZipOutputStream(httpResponse.getOutputStream()); OutputStream out =null) {
            //下载压缩包
            httpResponse.setContentType("application/zip");
            httpResponse.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("随便.zip", "UTF-8"));
            // 创建 ZipEntry 对象
            for (Map map:fileList){
                ZipEntry zipEntry =  new ZipEntry((String) map.get("nameShow"));
                zipOutputStream.putNextEntry(zipEntry);
                zipOutputStream.write((byte[]) map.get("outByte"));
            }
        } catch (IOException e) {
            //日志输出
            log.error(e.getMessage(), e);
        }
    }

    @Override
    @DataScope(deptAlias = "u",userAlias = "u")
    public List<StuCertificate> selectAllocatedList(StuCertificate stuCertificate) {
        return stuCertificateMapper.selectAllocatedList(stuCertificate);
    }

    @Override
    @DataScope(deptAlias = "u",userAlias = "u")
    public List<StuCertificate> selectUnallocatedList(StuCertificate stuCertificate) {
        return stuCertificateMapper.selectUnallocatedList(stuCertificate);
    }
    @Override
    @DataScope(deptAlias = "u",userAlias = "u")
    public ArrayList<Echarts> IsExpiredCount(StuCertificate stuCertificate){
        return stuCertificateMapper.IsExpiredCount(stuCertificate);
    }
}
